<template>
  <ant-modal
    modalWidth="1000"
    modalHeight="600"
    :visible="open"
    modal-title="工序人员"
    :adjust-size="true"
    @cancel="cancel"
  >
    <a-row slot="content">
      <a-col :span="24">
        <a-card :bordered="false" style="min-height:calc(100vh - 125px);">
          <select-user selectModel="multi" v-model="selectedUser" v-show="false" ref="selectUserRef" @callBack='saveSelectUser'/>
          <advance-table
            :columns="roleUserColumns"
            :data-source="subList"
            title="工序人员"
            :loading="subLoading"
            rowKey="id"
            size="middle"
            tableKey="system-roleuser-SysRoleIndex-table"
            @refresh="getUserList"
            :format-conditions="true"
            :row-selection="{ selectedRowKeys: selectedSubRowKeys, onChange: onSelectSubChange}"
            :pagination="{
              current: querySubParam.pageNum,
              pageSize: querySubParam.pageSize,
              total: subTotal,
              showSizeChanger: true,
              showLessItems: true,
              showQuickJumper: true,
              showTotal: (subTotal, range) => `第 ${range[0]}-${range[1]} 条，总计 ${subTotal} 条`,
              onChange: changeSubSize,
              onShowSizeChange: onShowSizeSubChange,
            }">
            <div class="table-operations" slot="button">
              <a-input-search
                placeholder="请输入编码或名称"
                v-model="querySubParam.userNameOrName"
                style="width: 150px"
                @search="handleQueryRoleUser" />
              <a-button
                type="primary"
                size="small"
                @click="handleAddUser"
                v-hasPermi="['biz:bizProductionProcess:user_add']">
                <a-icon type="plus" />添加用户
              </a-button>
              <a-button
                type="danger"
                v-if="!subMultiple"
                @click="handleDeleteSub"
                v-hasPermi="['biz:bizProductionProcess:remove']">
                <a-icon type="delete" />删除
              </a-button>
            </div>

            <span slot="status" slot-scope="{record}">
              <a-badge status="processing" :text=" statusFormat(record) " />
            </span>
            <span slot="roleKey" slot-scope="{text}">
              <a-tag color="blue">
                {{ text }}
              </a-tag>
            </span>
            <span slot="operation" slot-scope="{text, record}">
              <a @click.stop="handleDeleteSub(record)" v-hasPermi="['biz:bizProductionProcess:user_remove']">
                删除
              </a>
            </span>
          </advance-table>
        </a-card>
      </a-col>
    </a-row>

    <template slot="footer">
      <a-button  @click="cancel">
        关闭
      </a-button>
    </template>
  </ant-modal>
</template>
<script>
  import AdvanceTable from '@/components/pt/table/AdvanceTable'
  import SelectUser from './SelectUser'
  import AntModal from '@/components/pt/dialog/AntModal'
  import { listBizProcessUser,addBizProcessUser,delBizProcessUser } from '@/api/biz/bizProcessUser'
  export default {
    name: 'ProcessUser',
    components: {
      AdvanceTable,
      SelectUser,
      AntModal
    },
    data () {
      return {
        open:false,
        deptId:undefined,
        processId:undefined,
        // 表格缓存的数据 - 用来点击取消时回显数据
        cacheData: [],
        deleteData: [], // 可编辑表格待删除数据，数据库已存在数据界面假删除，保存到该集合，最终请求数据库删除
        subList: [],
        selectedRowKeys: [],
        selectedSubRowKeys: [],
        selectedRows: [],
        selectedSubRows: [],
        selectedUser: '',
        // 高级搜索 展开/关闭
        advanced: false,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        subMultiple: true,
        selectItem: {},
        ids: [],
        subIds: [], // 子表选择id集合
        loading: false,
        subLoading: false,
        total: 0,
        subTotal: 0,
        // 日期范围
        dateRange: [],
        labelCol: {
          span: 6
        },
        wrapperCol: {
          span: 18
        },
        queryParam: {
          pageNum: 1,
          pageSize: 10,
          roleName: undefined,
          roleKey: undefined,
          status: undefined
        },
        querySubParam: {
          pageNum: 1,
          pageSize: 10
        },
        addModalRefName: 'addModal', // 添加弹窗ref名称
        columns: [{
            title: '角色名称',
            dataIndex: 'roleName',
            ellipsis: true,
            scopedSlots: {
              customRender: 'roleNameSolt'
            }
          },
          {
            title: '角色编码',
            dataIndex: 'roleKey',
            width: '150px',
            ellipsis: true,
            scopedSlots: {
              customRender: 'roleKey'
            }
          },
          {
            title: '排序号',
            dataIndex: 'sort',
            align: 'center',
            scopedSlots: {
              customRender: 'sort'
            }
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: {
              customRender: 'status'
            },
            align: 'center'
          },
          {
            title: '操作',
            dataIndex: 'operation',
            width: '100px',
            scopedSlots: {
              customRender: 'operation'
            }
          }
        ],
        roleUserColumns: [{
            title: '姓名',
            dataIndex: 'name',
            ellipsis: true
          },
          {
            title: '编号',
            dataIndex: 'no',
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'operation',
            width: '100px',
            scopedSlots: {
              customRender: 'operation'
            }
          }
        ]
      }
    },
    filters: {},
    created () {
    },
    computed: {},
    methods: {
      getUserList () {
        // 只有保存的数据才加载字表数据
        this.subLoading = true
        this.querySubParam.processId = this.processId
        listBizProcessUser(this.querySubParam).then(response => {
          this.subList = response.data.list
          this.subTotal = response.data.total
          this.subLoading = false
        })
        this.subIds = []
        this.selectedSubRowKeys = []
        this.subMultiple = true
      },
      /** 搜索按钮操作 */
      handleQuery () {
        this.queryParam.pageNum = 1
        this.getList()
      },
      handleQueryRoleUser () {
        this.querySubParam.pageNum = 1
        this.getUserList()
      },
      selectFirstRecord () {
        // 定位选中行到第一条数据
        if (this.list.length > 0) {
           this.selectItem = this.list[0]
        } else {
          // 移除子表数据
           this.subList = []
           this.subTotal = 0
        }
      },
      handleAddUser () {
        this.$nextTick(() => (
          this.$refs.selectUserRef.showSelectUser(this.deptId)
        ))
      },
      onShowSizeChange (current, pageSize) {
        this.queryParam.pageSize = pageSize
        this.getList()
      },
      onShowSizeSubChange (current, pageSize) {
        this.querySubParam.pageSize = pageSize
        this.getUserList()
      },
      onSizeChange (current, size) {
        this.queryParam.pageNum = 1
        this.queryParam.pageSize = size
        this.getList()
      },
      changeSize (current, pageSize) {
        this.queryParam.pageNum = current
        this.queryParam.pageSize = pageSize
        this.getList()
      },
      changeSubSize (current, pageSize) {
        this.querySubParam.pageNum = current
        this.querySubParam.pageSize = pageSize
        this.getUserList()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
        this.ids = this.selectedRows.map(item => item.id)
        this.single = selectedRowKeys.length !== 1
        this.multiple = !selectedRowKeys.length
      },
      onSelectSubChange (selectedSubRowKeys, selectedSubRows) {
        this.selectedSubRowKeys = selectedSubRowKeys
        this.selectedSubRows = selectedSubRows
        this.subIds = this.selectedSubRows.map(item => item.id)
        this.subMultiple = !selectedSubRowKeys.length
      },
      handleDeleteSub (row) {
         var that = this
        const userIds = row.id || this.subIds
        this.$confirm({
          title: '确认删除所选中数据?',
          onOk () {
             return delBizProcessUser(userIds)
              .then(() => {
                that.onSelectSubChange([], [])
                that.getUserList()
                that.$message.success(
                  '删除成功',
                  3
                )
              })
          },
          onCancel () {}
        })
      },
      handleSetUser(processId,deptId) {
        this.open = true
        this.processId=processId;
        this.getUserList();
        this.deptId=deptId;
      },
      cancel () {
        this.open = false
        this.$emit('close')
      },
      saveSelectUser(user) {
        let ids = user.ids;
        let idArr = ids.split(";");
        let names = user.names;
        let nameArr = names.split(";");
        let defaultUsers = this.subList.map(v=>v.userId)
        let paramList=[];
        idArr.forEach(id=>{
          if(!defaultUsers.includes(id)){
            paramList.push({userId:id,processId:this.processId})
          }
        })
        if(!paramList.length){
          this.$message.error('所选人员已存在！')
          return;
        }
        addBizProcessUser(paramList).then(res=>{
          this.getUserList(this.processId);
        })
      }
    }
  }
</script>
<style lang="less">
  .ant-table-row.row-selection {
    background-color: #F0F2F5;
  }
</style>
